<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search
      ref="customSearchRef"
      v-slot="{ params }"
      :default-params="{ adCode: [], handoverTime: [], status: '1' }"
      @submit="handleSeachTable"
    >
      <t-col :span="3">
        <t-form-item label="装修类别" name="decorationType">
          <t-select
            v-model:value="params.decorationType"
            :options="dictionaryStore.get('decoration_order_type')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="房屋户型" name="houseType">
          <t-select
            v-model:value="params.houseType"
            :options="dictionaryStore.get('decoration_order_house_type')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="来源渠道" name="channelSource">
          <t-select
            v-model:value="params.channelSource"
            :options="dictionaryStore.get('clue_channel')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="归属城市" name="adCode">
          <t-cascader
            v-model:value="params.adCode"
            :options="city.tree"
            :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
            placeholder=""
            filterable
            clearable
            check-strictly
            value-type="full"
            @change="(value: any) => handleAdCodeChange(value, params)"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="楼盘名称" name="propertyName">
          <t-select v-model:value="params.propertyName" clearable filterable placeholder="">
            <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
              {{ _.name }}
              <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
            </t-option>
          </t-select>
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="详细地址" name="address">
          <t-input v-model:value="params.address" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="客户名称" name="name">
          <t-input v-model:value="params.name" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="手机号码" name="phone">
          <t-input v-model:value="params.phone" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="微信号码" name="wxCode">
          <t-input v-model:value="params.wxCode" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="性别" name="sex">
          <t-select
            v-model:value="params.sex"
            :options="dictionaryStore.get('system_user_sex')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="交房时间" name="handoverTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.handoverTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="审核状态" name="status">
          <t-select
            v-model:value="params.status"
            :options="dictionaryStore.get('clue_status')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="createTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.createTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      v-model:selected-row-keys="selectedRowKeys"
      row-key="id"
      :columns="columns"
      :api="clueListCRUD.page"
      column-controller-key="clueList"
      :reserve-selected-row-on-paginate="false"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button v-permission="['system:clue:create']" @click="handleOpenDialog('create', { adCode: [] })">
            新建线索
          </t-button>
          <!-- 分配线索 -->
          <allocation-clue :ids="selectedRowKeys" batch @request-success="handleDialogRequestSuccess" />
        </div>
      </template>
      <template #decorationType="{ row }">
        {{ dictionaryStore.analysis('decoration_order_type', row.decorationType) }}
      </template>
      <template #houseType="{ row }">
        {{ dictionaryStore.analysis('decoration_order_house_type', row.houseType) }}
      </template>
      <template #channelSource="{ row }">
        {{ dictionaryStore.analysis('clue_channel', row.channelSource) }}
      </template>
      <template #adCode="{ row }">
        {{ analysisCity(row) }}
      </template>
      <template #propertyName="{ row }">
        {{ propertyInfoList.find((item) => item.id === row.propertyName)?.name }}
        <span style="color: gray;">{{ row.address }}</span>
      </template>
      <template #saleId="{ row }">
        {{ userStore.getUserNameById(row.saleId) }}
      </template>
      <template #sex="{ row }">
        {{ dictionaryStore.analysis('system_user_sex', row.sex) }}
      </template>
      <template #status="{ row }">
        {{ dictionaryStore.analysis('clue_status', row.status) }}
      </template>
      <template #handoverTime="{ row }">
        {{ row.handoverTime && dayjs(row.handoverTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <!-- <t-link
            v-permission="['system:clue:query']"
            theme="primary"
            @click="handleOpenDialog('read', { id: row.id })"
          >
            详情
          </t-link> -->
          <t-link
            v-permission="['system:clue:update']"
            theme="primary"
            @click="handleOpenDialog('update', { id: row.id })"
          >
            编辑
          </t-link>
          <!-- 分配线索 -->
          <allocation-clue :ids="[row.id]" @request-success="handleDialogRequestSuccess" />
          <!-- 审核线索 -->
          <approve-clue v-if="row.status === 1" :id="row.id" @request-success="handleDialogRequestSuccess" />
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link v-permission="['system:clue:delete']" theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="clueListCRUD"
      header="*线索"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      <t-form-item label="装修类别" name="decorationType" :rules="[{ required: true, message: '请选择装修类别' }]">
        <t-select
          v-model:value="formData.decorationType"
          :options="dictionaryStore.get('decoration_order_type')"
          placeholder="请选择装修类别"
          clearable
          filterable
          :readonly="readonly"
          @clear="formData.decorationType = null"
        />
      </t-form-item>
      <t-form-item label="房屋户型" name="houseType" :rules="[{ required: true, message: '请选择房屋户型' }]">
        <t-select
          v-model:value="formData.houseType"
          :options="dictionaryStore.get('decoration_order_house_type')"
          placeholder="请选择房屋户型"
          clearable
          filterable
          :readonly="readonly"
          @clear="formData.houseType = null"
        />
      </t-form-item>
      <t-form-item label="来源渠道" name="channelSource" :rules="[{ required: true, message: '请选择来源渠道' }]">
        <t-select
          v-model:value="formData.channelSource"
          :options="dictionaryStore.get('clue_channel')"
          placeholder="请选择来源渠道"
          clearable
          filterable
          :readonly="readonly"
          @clear="formData.channelSource = null"
        />
      </t-form-item>
      <t-form-item label="归属城市" name="adCode" :rules="[{ required: true, message: '请选择归属城市' }]">
        <t-cascader
          v-model:value="formData.adCode"
          :options="city.tree"
          :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
          placeholder="请选择归属城市"
          filterable
          clearable
          :readonly="readonly"
          value-type="full"
          @change="(value: any) => handleAdCodeChange(value, formData)"
        />
      </t-form-item>
      <t-form-item label="楼盘名称" name="propertyName" :rules="[{ required: true, message: '请选择楼盘名称' }]">
        <t-select
          v-model:value="formData.propertyName"
          v-model:popup-visible="formData.popupVisible"
          placeholder="请选择楼盘名称"
          clearable
          filterable
          :readonly="readonly"
          @clear="formData.propertyName = null"
        >
          <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
            {{ _.name }}
            <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
          </t-option>
          <template #panelBottomContent>
            <!-- 快捷添加楼盘信息 -->
            <quick-add-property-info
              @open="formData.popupVisible = false"
              @close="((formData.popupVisible = true), handleGetPropertyInfoList())"
            />
          </template>
        </t-select>
      </t-form-item>
      <t-form-item label="详细地址" name="address">
        <t-input v-model:value="formData.address" placeholder="请输入详细地址" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="房屋面积(㎡)" name="houseArea" :rules="[{ required: true, message: '请输入房屋面积' }]">
        <t-input-number
          v-model:value="formData.houseArea"
          placeholder="请输入房屋面积"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="客户名称" name="name" :rules="[{ required: true, message: '请输入客户名称' }]">
        <t-input v-model:value="formData.name" placeholder="请输入客户名称" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item
        label="手机号码"
        name="phone"
        :rules="[
          { required: !formData.wxCode, message: '请输入手机号码' },
          { telnumber: true, message: '请输入正确的手机号码' },
        ]"
      >
        <t-input
          v-model:value="formData.phone"
          placeholder="请输入手机号码"
          clearable
          :readonly="readonly"
          maxlength="11"
        />
      </t-form-item>
      <t-form-item label="微信号码" name="wxCode" :rules="[{ required: !formData.phone, message: '请输入微信号码' }]">
        <t-input v-model:value="formData.wxCode" placeholder="请输入微信号码" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="性别" name="sex" :rules="[{ required: true, message: '请选择性别' }]">
        <t-select
          v-model:value="formData.sex"
          :options="dictionaryStore.get('system_user_sex')"
          placeholder="请选择性别"
          clearable
          filterable
          :readonly="readonly"
          @clear="formData.sex = null"
        />
      </t-form-item>
      <t-form-item label="交房时间" name="handoverTime" :rules="[{ required: true, message: '请选择交房时间' }]">
        <t-date-picker 
          allow-input
          v-model:value="formData.handoverTime"
          clearable
          placeholder="请选择交房时间"
          style="width: 100%"
          :readonly="readonly"
        />
      </t-form-item>
    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'ClueList',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { onMounted, onUpdated, ref, useTemplateRef } from 'vue';

import { propertyManageCRUD } from '@/api/config/property';
import { clueListCRUD } from '@/api/distribution/clue';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import QuickAddPropertyInfo from '@/pages/config/property/components/QuickAddPropertyInfo.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import city from '@/utils/city';
import disposableParams from '@/utils/disposableParams';

import AllocationClue from './components/AllocationClue.vue';
import ApproveClue from './components/ApproveClue.vue';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();
// 选中行的keys
const selectedRowKeys = ref([]);
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'row-select', type: 'multiple', width: 50 },
  { colKey: 'id', title: '线索ID' },
  { colKey: 'decorationType', title: '装修类别', width: 100 },
  { colKey: 'houseType', title: '房屋户型', width: 100 },
  { colKey: 'channelSource', title: '来源渠道', width: 100 },
  { colKey: 'adCode', title: '归属城市', width: 250 },
  { colKey: 'propertyName', title: '楼盘名称', width: 200 },
  // { colKey: 'address', title: '详细地址', width: 100 },
  { colKey: 'saleId', title: '客服', width: 100 },
  { colKey: 'houseArea', title: '房屋面积(㎡)', width: 120 },
  { colKey: 'name', title: '客户名称', width: 100 },
  { colKey: 'phone', title: '客户手机号', width: 120 },
  { colKey: 'wxCode', title: '客户微信', width: 100 },
  { colKey: 'sex', title: '性别', width: 100 },
  { colKey: 'status', title: '状态', width: 100 },
  { colKey: 'handoverTime', title: '交房时间', width: 180 },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 160, fixed: 'right' },
];
const handleSeachTable=(params:any) =>{
  disposableParams.set('to-do-tree-jump-params', {
    clueIds: '',
  });
  handleInitTable()
}
// 处理初始化表格
const handleInitTable = () => {
  // 待办树跳转参数
  const toDoTreeJumpParams = disposableParams.get('to-do-tree-jump-params');
  const params = {
    clueIds: toDoTreeJumpParams.clueIds,
    ...customSearchRef.value.params,
  };
  if (!params.adCode.length) {
    delete params.province;
    delete params.city;
    delete params.area;
  }
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
onUpdated(() => {
  handleRefreshTable()
})
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  handleGetPropertyInfoList();
  customDialogRef.value.open(mode, params);
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  params.adCode = [];
  if (params.province) params.adCode.push(params.province);
  if (params.city) params.adCode.push(params.city);
  if (params.area) params.adCode.push(params.area);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  clueListCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理归属城市改变
const handleAdCodeChange = (value: string[], params: Record<string, any>) => {
  params.province = value[0] || '';
  params.city = value[1] || '';
  params.area = value[2] || '';
};
// 解析城市
const analysisCity = (row: Record<string, any>) => {
  let result = '';
  if (row.province) {
    result += city.list.find((item) => item.adcode === row.province).name;
  }
  if (row.city) {
    result += ` / ${city.list.find((item) => item.adcode === row.city).name}`;
  }
  if (row.area) {
    result += ` / ${city.list.find((item) => item.adcode === row.area).name}`;
  }
  return result;
};
</script>

<style lang="less" scoped></style>
